package com.groupbuying.storeinternal.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.groupbuying.storeinternal.connector.CoustomerFeign;
import com.groupbuying.storeinternal.connector.WechatAliFeign;
import com.groupbuying.storeinternal.constants.CommonConstants;
import com.groupbuying.storeinternal.constants.StoreAccountWxinfoRelEnumConstants;
import com.groupbuying.storeinternal.context.FilterContextHandler;
import com.groupbuying.storeinternal.dao.*;
import com.groupbuying.storeinternal.domain.*;
import com.groupbuying.storeinternal.dto.StoreCapitalVirtualAccountDetaiDTO;
import com.groupbuying.storeinternal.service.StoreInternalAccountService;
import com.groupbuying.storeinternal.service.forManage.StoreMenuService;
import com.groupbuying.storeinternal.utils.*;
import com.groupbuying.storeinternal.utils.apiresult.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * @author ywxd
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class StoreInternalAccountServiceImpl implements StoreInternalAccountService {

    @Autowired
    private StoreAccountWxinfoRelDao storeAccountWxinfoRelDao;
    @Autowired
    private WechatAliFeign wechatAliFeign;
    @Autowired
    StoreMenuService storeMenuService;
    @Autowired
    StoreAccountDao accountMapper;
    @Autowired
    StoreCheckoutCounterDao storeCheckoutCounterDao;
    @Autowired
    StoreCheckoutCounterRelDao storeCheckoutCounterRelDao;
    @Autowired
    StoreCapitalVirtualAccountDetailDao storeCapitalVirtualAccountDetailDao;
    private static final Logger logger = LoggerFactory.getLogger(StoreInternalAccountService.class);





    @Override
    public ApiResult loginForStore(Map<String, Object> param) {
        logger.info("===============START===========商户登录开始===========");
        Object temp = param.get("username");
        String username = temp == null ? "" : temp.toString();
        temp = param.get("pwd");
        String pwd = temp == null ? "" : temp.toString();
        //不再校验code
        temp = param.get("code");
        String code = temp == null ? "" : temp.toString();
        //部分传openId
        temp = param.get("openId");
        String openId = temp == null ? "" : temp.toString();

        String password = MD5Utils.encrypt(username, pwd);
        StoreAccountDO accountDO = this.getByAccountName(username);

        if (null == accountDO) {
            return ApiResult.failure("该用户不存在");
        }

        if (!accountDO.getPassword().equals(password)) {
            return ApiResult.failure("密码错误");
        }
        if(("1").equals(accountDO.getFreezestatus())){
            return ApiResult.failure("该账号已冻结");
        }

        logger.info("账户I:{},{},{}", accountDO.getAccountId(), accountDO.getAccountName(), accountDO.getAccountNo());

        if(code != null && !code.equals("")){
            //获取公众号的OpenId
            Map<String,Object> resOpenId = wechatAliFeign.getMPOpenidByCode(code,"youdianproductor");
            openId = resOpenId.get("openid")==null?null:resOpenId.get("openid").toString();
            logger.info("用户获取openId:{}", openId);
            if (StringUtils.isEmpty(openId)) {
                logger.error("用户：{}登陆成功,code：{},openId获取失败", accountDO.getAccountId(), code);
                //return ApiResult.failure("openId获取失败");
            }
        }
        
        StoreAccountWxinfoRelDO storeAccountWxinfoRelDO = storeAccountWxinfoRelDao.getByAccountAndOpen(accountDO.getAccountId(), openId);
        StoreAccountWxinfoRelDO storeAccountWxinfoRel = new StoreAccountWxinfoRelDO();
        try {
            //openid不为空则创建微信关系
            if (storeAccountWxinfoRelDO == null && !StringUtils.isEmpty(openId)) {
                storeAccountWxinfoRel.setAccountId(accountDO.getAccountId());
                storeAccountWxinfoRel.setOpenId(openId);
                storeAccountWxinfoRel.setGmtCreate(new Date());
                storeAccountWxinfoRel.setGmtModified(new Date());
                storeAccountWxinfoRel.setIsDelete(StoreAccountWxinfoRelEnumConstants.ENUM_ISDELETE_UNDEL);
                storeAccountWxinfoRelDao.save(storeAccountWxinfoRel);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        UserToken userToken = new UserToken(accountDO.getAccountName(), accountDO.getAccountId(), accountDO.getProviderId(), accountDO.getAgentId());

        String token = "";
        try {
            token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 60 * 60 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map map = new HashMap();
        map.put("openId", openId);
        map.put("token", token);
        map.put("perms", storeMenuService.PermsByUserId(accountDO.getAccountId()));
        map.put("router", storeMenuService.RouterDTOsByUserId(accountDO.getAccountId()));

        return ApiResult.success(map);
    }

    @Override
    public StoreAccountDO getByAccountName(String accountName) {
        Map map_repeat = new HashMap();
        map_repeat.put("accountName", accountName);
        List<StoreAccountDO> list_repeat = accountMapper.list(map_repeat);
        if (list_repeat.size() > 0) {
            return list_repeat.get(0);
        }
        return null;
    }

    @Override
    public ApiResult getFlowStore(Map<String, String> map) {
        String parStart = map.get("gmtCreateStart");
        String parEnd = map.get("gmtCreateEnd");
        String checkstandId = null;
        String storeUuid = null;
        String accountId = FilterContextHandler.getUserID();

        StoreCheckoutCounterRelDO storeCheckoutCounterRelDO = storeCheckoutCounterRelDao.getUshop(accountId);
        if (storeCheckoutCounterRelDO != null) {
            checkstandId = storeCheckoutCounterRelDO.getCounteruuid();
        }
        logger.info("收银台ID" + checkstandId);
        StoreCheckoutCounterDO storeCheckoutCounterDO = storeCheckoutCounterDao.get(checkstandId);
        if (storeCheckoutCounterDO != null) {
            storeUuid = storeCheckoutCounterDO.getStoreuuid();

        }
        Map<String, Object> queryMap = new HashMap<>();
        if (!StringUtils.isEmpty(parStart) && !StringUtils.isEmpty(parEnd)) {
            //格式化开始时间
            parStart = DateUtils.format(new Date(Long.valueOf(parStart)), DateUtils.YMD);
            //传入的结束时间增加一天用于between查询的后开问题
            parEnd = DateUtils.format(new Date(Long.valueOf(parEnd) + 24 * 60 * 60 * 1000), DateUtils.YMD);
            queryMap.put("gmtCreateStart", parStart);
            queryMap.put("gmtCreateEnd", parEnd);
        }
        String[] inOrOut = {"0", "1","3"};

        queryMap.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        queryMap.put("storeUuid", storeUuid);
        queryMap.put("inOrOut", inOrOut);
        queryMap.put("page",map.get("page"));
        queryMap.put("limit",map.get("limit"));
        Query query = new Query(queryMap);

        List<StoreCapitalVirtualAccountDetaiDTO> storeCapitalVirtualAccountDetail = new ArrayList<>();
        List<StoreCapitalVirtualAccountDetailDO> storeCapitalVirtualAccountDetailList = storeCapitalVirtualAccountDetailDao.getStoreFlowListByStoreUuid(query);
        StoreCapitalVirtualAccountDetaiDTO dto = null;
        for (StoreCapitalVirtualAccountDetailDO store : storeCapitalVirtualAccountDetailList) {
            dto = new StoreCapitalVirtualAccountDetaiDTO(store);
            storeCapitalVirtualAccountDetail.add(dto);
        }
        int total = storeCapitalVirtualAccountDetailDao.countForFlow(query);
        PageUtils pageUtils = new PageUtils(storeCapitalVirtualAccountDetail, total);
        return ApiResult.success(pageUtils);
    }
}
